package com.locatme.fragment;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.locatme.adapter.PagesViewAdapter;
import com.locatme.model.Evenement;
import com.locatme.model.Utilisateur;
import com.locatme.modelBD.EvenementBD;
import com.locatme.modelBD.ListeAmisBD;
import com.main.locatme.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class PagesFragment extends Fragment implements View.OnClickListener {
    // declare  the variables to Show/Set the date and time when Time and  Date Picker Dialog first appears
    private int mYear, mMonth, mDay, mHour, mMinute;
    private TextView startHour, endHour, dateS, dateE, adr, eventName;
    private final SimpleDateFormat formaterDate = new SimpleDateFormat("dd/MM/yy");
    private final SimpleDateFormat formaterHour = new SimpleDateFormat("hh:mm");
    ImageView imgHStart, imgCalStart, imgHEnd, imgCalEnd, imgAdr, imgAddF;
    Button createButton;
    Button buttonOk;
    private CharSequence[] items;
    private ListView listView;
    private ListeAmisBD amisBD;
    private List<String> listAmis;
    private Utilisateur user;
    private Evenement evenement;
    private EvenementBD evenementBD;

    public PagesFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        user = (Utilisateur) getActivity().getIntent().getExtras().getParcelable("user");
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
        View rootView = inflater.inflate(R.layout.fragment_pages, container, false);
        startHour = (TextView) rootView.findViewById(R.id.textStartHour);
        startHour.setText(formaterHour.format(c.getTime()));
        endHour = (TextView) rootView.findViewById(R.id.textEndHour);
        endHour.setText(formaterHour.format(c.getTime()));
        dateS = (TextView) rootView.findViewById(R.id.textCalS);
        dateS.setText(formaterDate.format(c.getTime()));
        dateE = (TextView) rootView.findViewById(R.id.textCalE);
        dateE.setText(formaterDate.format(c.getTime()));
        adr = (TextView) rootView.findViewById(R.id.textAdr);
        adr.setText("Adress of meeting point");
        buttonOk= (Button) rootView.findViewById(R.id.buttonCreateOK);
        createButton = (Button) rootView.findViewById(R.id.buttonCreateEvent);
        eventName = (TextView) rootView.findViewById(R.id.editEventName);

        if (rootView != null) {
            imgHStart = (ImageView) rootView.findViewById(R.id.imageClockS);
            imgHEnd = (ImageView) rootView.findViewById(R.id.imageClockE);
            imgCalStart = (ImageView) rootView.findViewById(R.id.imageCalS);
            imgCalEnd = (ImageView) rootView.findViewById(R.id.imageCalE);
            imgAdr = (ImageView) rootView.findViewById(R.id.imageAdr);
            imgAddF = (ImageView) rootView.findViewById(R.id.imageAddPerson);
        }
        imgHStart.setOnClickListener(this);
        imgHEnd.setOnClickListener(this);
        imgCalStart.setOnClickListener(this);
        imgCalEnd.setOnClickListener(this);
        imgAdr.setOnClickListener(this);
        imgAddF.setOnClickListener(this);

        setAmisBD(new ListeAmisBD(getActivity()));
        getAmisBD().open();
        listAmis = new ArrayList<String>();
        ;
        listAmis = getAmisBD().getFriendByLogin(user.getLogin());
        List<String> valuesFriends = listAmis;
        List<String> valuesT = new ArrayList<String>();
        valuesT.add("Event 1");
        valuesT.add("Event 2");
        valuesT.add("Event 3");
        valuesT.add("Event 4");
        valuesT.add("Event 5");
        valuesT.add("Event 6");
        valuesT.add("Event 7");
        valuesT.add("Event 8");
        valuesT.add("Event 9");

        // use your custom layout
        listView = (ListView) rootView.findViewById(R.id.list);
        PagesViewAdapter adapter = new PagesViewAdapter(this.getActivity(), valuesT);
        listView.setAdapter(adapter);

        buttonOk.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!eventName.getText().toString().equals("Event Name") && !adr.getText().toString().equals("Adress of the metting") && !adr.getText().toString().equals("") && !eventName.getText().toString().equals("")){
                    evenement = new Evenement(eventName.getText().toString(), adr.getText().toString(), dateS.getText().toString(), dateE.getText().toString(), startHour.getText().toString(), endHour.getText().toString(), user.getLogin());
                evenementBD.open();
                evenementBD.insertEvenement(evenement);
                evenementBD.close();
                Toast.makeText(getActivity(), "Event created", Toast.LENGTH_LONG);
            }else{
                Toast.makeText(getActivity(), "Missing Event infos", Toast.LENGTH_LONG);

            }
        }
        });

        return rootView;
    }

    @Override
    public void onClick(View v) {

        if (v == imgCalStart || v == imgCalEnd) {
            final View actualV = v;
            // Process to get Current Date
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);

            // Launch Date Picker Dialog
            DatePickerDialog dpd = new DatePickerDialog(this.getActivity(),
                    new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year,
                                              int monthOfYear, int dayOfMonth) {
                            // Display Selected date in textbox
                            if (actualV == imgCalStart) {
                                c.set(year, monthOfYear, dayOfMonth);
                                dateS.setText(formaterDate.format(c.getTime()));
                            } else {
                                c.set(year, monthOfYear, dayOfMonth);
                                dateE.setText(formaterDate.format(c.getTime()));
                            }
                        }
                    }, mYear, mMonth, mDay);
            dpd.show();
        }

        if (v == imgHStart || v == imgHEnd) {
            final View actualV = v;
            // Process to get Current Time
            final Calendar c = Calendar.getInstance();
            mHour = c.get(Calendar.HOUR_OF_DAY);
            mMinute = c.get(Calendar.MINUTE);

            // Launch Time Picker Dialog
            TimePickerDialog tpd = new TimePickerDialog(this.getActivity(),
                    new TimePickerDialog.OnTimeSetListener() {

                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay,
                                              int minute) {
                            // Display Selected time in textbox
                            if (actualV == imgHStart) {
                                c.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, hourOfDay, minute);
                                startHour.setText(formaterHour.format(c.getTime()));
                            } else {
                                c.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, hourOfDay, minute);
                                endHour.setText(formaterHour.format(c.getTime()));
                            }
                        }
                    }, mHour, mMinute, true);
            tpd.show();
        }

        if (v == imgAdr) {
            // get prompts.xml view
            LayoutInflater li = LayoutInflater.from(this.getActivity());
            View promptsView = li.inflate(R.layout.prompts, null);

            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    this.getActivity());

            // set prompts.xml to alertdialog builder
            alertDialogBuilder.setView(promptsView);

            final EditText userInput = (EditText) promptsView
                    .findViewById(R.id.editTextDialogUserInput);

            // set dialog message
            alertDialogBuilder
                    .setCancelable(false)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    // get user input and set it to result
                                    // edit text
                                    adr.setText(userInput.getText());
                                }
                            })
                    .setNegativeButton("Cancel",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();
        }
        if (v == imgAddF) {

            items = listAmis.toArray(new CharSequence[listAmis.size()]);
            final boolean[] itemsChecked = new boolean[items.length];

            AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
            builder.setTitle("Choose your guest:");
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String selectedGuest = "Selected Guest:";
                    for (int i = 0; i < items.length; i++) {
                        if (itemsChecked[i]) {

                            selectedGuest = selectedGuest + items[i] + " ";
                            itemsChecked[i] = false;
                        }
                    }
                    Log.v("myapp", selectedGuest);
                }
            });

            builder.setMultiChoiceItems(items, new boolean[]{false, false, false}, new DialogInterface.OnMultiChoiceClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    itemsChecked[which] = isChecked;
                }
            });
            builder.show();
        }

        if (v == createButton) {
            Log.v("myapp", "OK");
            if (!eventName.getText().toString().equals("Event Name") && !adr.getText().toString().equals("Adress of the metting") && !adr.getText().toString().equals("") && !eventName.getText().toString().equals(""))
                evenement = new Evenement(eventName.getText().toString(), adr.getText().toString(), dateS.getText().toString(), dateE.getText().toString(), startHour.getText().toString(), endHour.getText().toString(), user.getLogin());
            evenementBD.open();
            evenementBD.insertEvenement(evenement);
            evenementBD.close();
            Toast.makeText(this.getActivity(), "Event created", Toast.LENGTH_LONG);
        } else {
            Toast.makeText(this.getActivity(), "Missing Event infos", Toast.LENGTH_LONG);

        }
    }



    public ListeAmisBD getAmisBD() {
        return amisBD;
    }

    public void setAmisBD(ListeAmisBD amisBD) {
        this.amisBD = amisBD;
    }
}

